package com.young.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.young.quartz.domain.dto.QuartzLogSearchDto;
import com.young.quartz.domain.entity.QuartzLogEntity;
import com.young.quartz.mapper.QuartzLogMapper;
import com.young.quartz.service.QrtzLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QrtzLogServiceImpl implements QrtzLogService {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private QuartzLogMapper quartzLogMapper;
    @Override
    public Map<String,Object> getQuartzLogList(QuartzLogSearchDto dto) {
        Page<QuartzLogEntity> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        IPage<QuartzLogEntity> selectPage = quartzLogMapper.getQuartzLogList(page, dto);
        List<QuartzLogEntity> records = selectPage.getRecords();
        long total = selectPage.getTotal();
        Map<String,Object> result = new HashMap<>();
        result.put("list",records);
        result.put("total",total);
        return result;
    }

    @Override
    public void retry(Integer logId) {
        QuartzLogEntity quartzLogEntity = quartzLogMapper.selectById(logId);
        if (quartzLogEntity!=null){
            try {
                String jobClassName = quartzLogEntity.getJobClassName();
                Class<?> clazz = Class.forName(jobClassName);
                Object bean = applicationContext.getBean(clazz);
                applicationContext.getAutowireCapableBeanFactory().autowireBean(bean);
                Method executeMethod = clazz.getDeclaredMethod("execute", QuartzLogEntity.class);
                executeMethod.invoke(bean,quartzLogEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
